#include"Song.h" 

#include"StatusBar.h"

#include<taglib/taglib.h>
#include<taglib/fileref.h>

#include<QFileInfo>
//#include<phonon/BackendCapabilities>

Song::Song(QString path):m_path(path){
	m_track = 0;
	m_duration = 0;
	
	//Those two can throw an exception
	_validateExists();
	_validatePlayable();
	
	m_isValid = true;//Assume valid until proven otherwise.
	TagLib::FileRef f(path.toUtf8().data());
	if(f.isNull()){//This should've been tested by _validateExists() already.
		m_isValid = false;
		return;
	}
	
	TagLib::Tag *tag = f.tag();
	
	if(tag == 0){
		m_isValid = false;
		return;
	}
	
	m_title = tag->title().toCString();
	m_artist = tag->artist().toCString();
	m_album = tag->album().toCString();
	
	m_track = tag->track();
	if(f.audioProperties())
		m_duration = f.audioProperties()->length() * 1000;
	
	if(m_title.isEmpty() || m_artist.isEmpty() || m_album.isEmpty())
		m_isValid = false;
}

Song::Song(QString path, QString title, QString artist, QString album, short int track, qint64 duration){
	m_path = path;
	m_title = title;
	m_artist = artist;
	m_album = album;
	m_track = track;
	m_duration = duration;
	
	if(m_path.isEmpty() || m_title.isEmpty() || m_artist.isEmpty() || m_album.isEmpty())
		throw SongException("Invalid song created through shortcut for " + m_path);
	m_isValid = true;
}

void Song::_validateExists(){
	QFileInfo fi(m_path);
	if(	  !fi.isFile()
		|| fi.isExecutable()
		|| fi.isHidden()
		||!fi.isReadable()
		|| fi.size() < 128
		)
		throw SongException("Song at " + m_path + " does not exist.");
}

void Song::_validatePlayable(){
	QFileInfo fi(m_path);
	//if(!Phonon::BackendCapabilities::isMimeTypeAvailable(fi.suffix())){
		/*QStringList capabilities = Phonon::BackendCapabilities::availableMimeTypes();
		bool found = false;
		QString suffix = fi.suffix();
		for(int i = 0; i < capabilities.size() && !found; i++)
			found = capabilities[i].contains(suffix) && (capabilities[i].contains("audio")||capabilities[i].contains("video"));
		if(!found)
			throw SongException("Unrecognized extension for song at " + m_path + ".");*/
	//}
}

Song::~Song(){
	emit deleted();
}


bool Song::isValid()const{
	return m_isValid;
}

SongData *Song::data()const{
	if(!isValid())
		return 0;
	
	SongData *ret = new SongData;
	ret->title = title();
	ret->artist = artist();
	ret->album = album();
	ret->trackno = track();
	ret->duration = duration();
	ret->path = path();
	return ret;
}

void Song::apply(QPointer<Song> other){
	if(other==0)
		return;

	m_isValid = other->m_isValid;
	m_title = other->m_title;
	m_artist = other->m_artist;
	m_album = other->m_album;
	m_track = other->m_track;
	m_duration = other->m_duration;
	m_path = other->m_path;//Although, this should never change
}
